package com.example.mediaservice;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;

import java.io.IOException;
import java.util.List;


public class PlaybackManager {
    private static final String TAG = "PlaybackManager";
    private final MediaSessionCompat mediaSession;
    private final List<MediaItem> mediaList;
    private int currentMediaIndex = 0;
    private boolean isPlaying = false;

    private long currentBarPosition = 0;
    private final Context context;
    private MediaPlayer mediaPlayer; //音频播放器

    public interface updateNotification { //回调接口
        void onUpdateNotification();
    }
    // 添加监听器字段和设置方法
    private updateNotification updateListener;
    public void setOnPlaybackUpdateListener(updateNotification listener) {
        this.updateListener = listener;
    }
    public PlaybackManager(MediaSessionCompat mediaSession, List<MediaItem> mediaList, Context context) {
        this.mediaSession = mediaSession;
        this.mediaList = mediaList;
        this.context = context;
        initMediaPlayer();// 初始化播放器
    }
    // 初始化MediaPlayer
    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        // 设置播放完成监听（自动播放下一首）
        mediaPlayer.setOnCompletionListener(mp -> {
            skipToNext();
            playCurrentMedia();
            if (updateListener != null) { // 回调状态栏监听器
                updateListener.onUpdateNotification();
            }
        });
        // 设置错误监听
        mediaPlayer.setOnErrorListener((mp, what, extra) -> {
            Log.e(TAG, "MediaPlayer error: " + what + ", " + extra);
            return false;
        });
    }



    // 播放当前选中的媒体
    public void playCurrentMedia() {

        if (mediaList == null || mediaList.isEmpty() ||
                currentMediaIndex < 0 || currentMediaIndex >= mediaList.size()) {
            Log.w(TAG, "No valid media to play");
            return;
        }

        try {
            MediaItem currentItem = mediaList.get(currentMediaIndex);
            // 根据媒体ID获取本地音频Uri（通过MediaStore）
            Uri audioUri = Uri.withAppendedPath(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    currentItem.id
            );
            // 避免重复准备
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            // 重置播放器并设置数据源
            mediaPlayer.reset();
            mediaPlayer.setDataSource(context, audioUri);
            mediaPlayer.prepareAsync(); // 异步准备，避免阻塞主线程

            // 准备完成后开始播放
            mediaPlayer.setOnPreparedListener(mp -> {
                mp.start();
                isPlaying = true;
                updateMediaMetadata();
                updatePlaybackState();
            });

        } catch (IOException e) {
            Log.e(TAG, "Failed to play media: " + e.getMessage());
            e.printStackTrace();
        }
    }
    // 播放/暂停切换
    public void togglePlayPause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            isPlaying = false;
        } else {
            mediaPlayer.start();
            isPlaying = true;
        }
        updatePlaybackState();
    }
    //更新媒体元数据
    public void updateMediaMetadata() {
        if (mediaList == null || mediaList.isEmpty() ||
                currentMediaIndex < 0 || currentMediaIndex >= mediaList.size()) {
            return;
        }
        // 获取当前媒体项并构建媒体元数据
        MediaItem item = mediaList.get(currentMediaIndex);
        MediaMetadataCompat metadata = new MediaMetadataCompat.Builder()
                .putString(MediaMetadataCompat.METADATA_KEY_TITLE, item.title)
                .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, item.artist)
                .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, item.duration)
                .build();
        mediaSession.setMetadata(metadata);
    }

    public void skipToNext() {
        Log.d(TAG, "skipToNext called");

        if (mediaList == null || mediaList.isEmpty()) {
            Log.w(TAG, "Media list is empty");
            return;
        }
        currentMediaIndex = (currentMediaIndex + 1) % mediaList.size();
//        updateMediaMetadata();
        Log.d(TAG, "Skipped to next track: " + currentMediaIndex);
        playCurrentMedia();
    }

    public void skipToPrevious() {
        Log.d(TAG, "skipToPrevious called");

        if (mediaList == null || mediaList.isEmpty()) {
            Log.w(TAG, "Media list is empty");
            return;
        }
//        currentBarPosition = 0;
        currentMediaIndex = (currentMediaIndex - 1 + mediaList.size()) % mediaList.size();
//        updateMediaMetadata();
        Log.d(TAG, "Skipped to previous track: " + currentMediaIndex);
        playCurrentMedia();
    }
    public void seekTo(long position) {
        if (mediaPlayer != null) {
            mediaPlayer.seekTo((int) position);
            currentBarPosition = position;
            updatePlaybackState(position);
        }
    }

    // 更新播放状态
    public void updatePlaybackState() {
        if (mediaPlayer != null) {
            currentBarPosition = mediaPlayer.getCurrentPosition();
        }
        updatePlaybackState(currentBarPosition);
    }

    // 更新播放状态（带位置参数）
    public void updatePlaybackState(long position) {
        this.currentBarPosition = position;
        int state = isPlaying ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
        // 构建播放状态对象，包含状态、位置、播放速度和可执行的操作
        PlaybackStateCompat playbackState = new PlaybackStateCompat.Builder()
                .setState(state, currentBarPosition, 1.0f)
                .setActions(PlaybackStateCompat.ACTION_PLAY |
                        PlaybackStateCompat.ACTION_PAUSE |
                        PlaybackStateCompat.ACTION_PLAY_PAUSE |
                        PlaybackStateCompat.ACTION_SKIP_TO_NEXT |
                        PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
                        PlaybackStateCompat.ACTION_SEEK_TO)
                .build();

        // 将构建好的播放状态设置到媒体会话中
        mediaSession.setPlaybackState(playbackState);
    }
    // 更新当前歌词显示

    public void setPlaying(boolean playing) {
        this.isPlaying = playing;
    }

    public boolean isPlaying() {
        return isPlaying;
    }
    public void setCurrentBarPosition(long position) {
        this.currentBarPosition = position;
    }

    public long getCurrentBarPosition() {
        return currentBarPosition;
    }

    public long getCurrentBarPositionFromState() {
        try {
            PlaybackStateCompat currentState = mediaSession.getController().getPlaybackState();
            if (currentState != null) {
                return currentState.getPosition();
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting current position from state: " + e.getMessage());
        }
        return currentBarPosition; // 返回内部跟踪的位置作为备选
    }
    public int getCurrentMediaIndex() {
        return currentMediaIndex;
    }

    // 释放资源
    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
